from django import forms
from django.core.exceptions import ValidationError

from web import models
from web.forms.bootstrap import BootStrapForm
from web.forms.widgets import ColorRadioSelect


class ProjectModelForm(BootStrapForm, forms.ModelForm):
    # attrs={'xxx': 'xxx'}属性展示，在页面中会显示xxx=xxx
    # desc = forms.CharField(label='项目描述', widget=forms.Textarea(attrs={'xxx': 'xxx'}))
    # color = forms.RadioSelect()

    bootstrap_class_exclude = ['color']

    class Meta:
        model = models.Project
        fields = ['name', 'color', 'desc']
        widgets = {
            'color': ColorRadioSelect(attrs={'class': 'color-radio'}),
            'desc': forms.Textarea,
        }

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_name(self):
        """项目校验"""
        name = self.cleaned_data.get('name')
        # 1. 判断当前用户是否已经创建过此项目
        project_obj = models.Project.objects.filter(creator=self.request.tracer.user, name=name).first()
        if project_obj:
            raise ValidationError('项目名已存在，请重新输入项目名')
        # 2. 当前用户是否还有额度进行创建项目？
        # 最多创建N个项目
        # self.request.tracer.price_policy.project_num
        # 现在已经创建多少项目？
        count = models.Project.objects.filter(creator=self.request.tracer.user).count()
        if count >= self.request.tracer.price_policy.project_num:
            raise ValidationError('项目个数超限，请购买套餐')
        return name
